//
//  TwoHomeViewController.swift
//  SwiftStudy
//
//  Created by chang on 2018/1/5.
//  Copyright © 2018年 chang. All rights reserved.
//  天气预报页面

import UIKit
import Alamofire
import SwiftyJSON
import CoreLocation

class TwoHomeViewController: UIViewController, CLLocationManagerDelegate {

    var weatherBgImage:UIImageView = UIImageView()
    let imageHeight:CGFloat = CCScaleW(w: 240)
    var origialFrame:CGRect = CGRect()
    var weatherLabel : UILabel!
    var tableView : UITableView!
    var hourly_forecastArray : NSArray?
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.isNavigationBarHidden = true
        self.view.backgroundColor = UIColor.defaultBackgroundColor
        self.layoutView()
        self.gLocation()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        locationManager.startUpdatingLocation()
    }
    
    func layoutView() {
        weatherBgImage = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: MAINSCREEN_WIDTH, height: imageHeight))
        weatherBgImage.image = UIImage.init(named: "t_weather_bg")
        self.view.addSubview(weatherBgImage)
        
        origialFrame = weatherBgImage.frame
        
        weatherLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: weatherBgImage.width, height: weatherBgImage.height))
        weatherLabel.backgroundColor = UIColor.clear
        weatherLabel.font = UIFont.systemFont(ofSize: 24)
        weatherLabel.textColor = UIColor.defaultBackgroundColor
        weatherLabel.textAlignment = .center
        weatherLabel.numberOfLines = 0
        weatherBgImage.addSubview(weatherLabel)
        
        tableView = UITableView.init(frame: CGRect.init(x:0, y:0, width:MAINSCREEN_WIDTH, height:self.view.height - self.tabBarHeight))
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
        
        let headView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: MAINSCREEN_WIDTH, height: weatherBgImage.height))
        headView.backgroundColor = UIColor.clear
        tableView.tableHeaderView = headView
    }
    
    //获取位置
    func gLocation() {
        locationManager.delegate = self
        locationManager.requestAlwaysAuthorization()
    }
    
    // MARK: - CLLocationManagerDelegate
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let latStr = String(format: "%f", (locations.last?.coordinate.latitude)!)
        let lonStr = String(format: "%f", (locations.last?.coordinate.longitude)!)
        
        let locationStr = latStr + "," + lonStr
        locationManager.stopUpdatingLocation()
        self.requestWeather(locationStr: locationStr)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        locationManager.stopUpdatingLocation()
        self.requestWeather(locationStr: "")
    }
    
    //请求天气信息
    func requestWeather(locationStr: String) -> Void {
        
        self.view.makeToastActivity(.center)
        var city = locationStr
        if city.isEmpty {
            city = "北京"
        }
        
        //百度的天气预报API接口，地址：http://api.map.baidu.com/telematics/v3/weather?location=%E5%90%88%E8%82%A5&output=json&ak=wl82QREF9dNMEEGYu3LAGqdU
        let url = "https://free-api.heweather.com/v5/weather"
        let param = ["city" : city, "key" : "951e900890d24d97937db9694df6c563"]
        
        Alamofire.request(url, method: .post, parameters: param).responseJSON {
            [weak self] response in
            
            self?.view.hideToastActivity()
            /***
            print("Request: \(String(describing: response.request))")   // original url request
            print("Response: \(String(describing: response.response))") // http url response
            print("Result: \(response.result)")                         // response serialization result
            
            if let json = response.result.value {
                print("JSON: \(json)") // serialized json response
            }
            
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)") // original server data as UTF8 string
            }
             ***/
            if let responseCC = response.result.value {
                let json = JSON(responseCC)
                let statusStr = json["HeWeather5",0,"status"]
                if statusStr.string == "ok" {
                    let basicDic = json["HeWeather5",0,"basic"]
                    let nowDic = json["HeWeather5",0,"now"]
                    
                    let city = basicDic["city"].string //城市名称
                    let tmp = nowDic["tmp"].string //当前温度
                    
                    self?.weatherLabel.text = city! + " " + tmp! + "°"
                    //每小时的预测
                    self?.hourly_forecastArray = JSON(json["HeWeather5",0,"hourly_forecast"]).arrayValue as NSArray
                    self?.tableView.reloadData()
                }
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


//MARK: -UITableViewDelegate,UITableViewDataSource
extension TwoHomeViewController :UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.hourly_forecastArray?.count ?? 0
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 54
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: identifier)
            cell?.selectionStyle = .none
            cell?.backgroundColor = UIColor.clear
            cell?.textLabel?.textColor = UIColor.defaultTextColor
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 15)
            
            let lineView = UIView.init(frame: CGRect.init(x: 0, y: 54-0.5, width: tableView.width, height: 0.5))
            lineView.backgroundColor = UIColor.defaultLineColor
            cell?.addSubview(lineView)
        }
        
        let dataDic = JSON(self.hourly_forecastArray?[indexPath.row] ?? NSDictionary.init()).dictionary
        let dateStr = dataDic?["date"]?.string
        let txtStr = dataDic?["cond"]?["txt"].string
        let dirStr = dataDic?["wind"]?["dir"].string
        let scStr = dataDic?["wind"]?["sc"].string
        
        cell?.textLabel?.text = dateStr! + "  " + txtStr! + "  " + dirStr! + "  " + scStr!
        
        return cell!
    }
    
    //MARK:UIScrollViewDelegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let y_offset = scrollView.contentOffset.y
        if y_offset > 0 {
            weatherBgImage.frame.origin.y = origialFrame.origin.y - y_offset
        }else{
            let height = self.origialFrame.size.height - y_offset
            let width = height/self.origialFrame.size.height * self.origialFrame.size.width
            let x = origialFrame.origin.x - (width-origialFrame.size.width)/2
            let frame = CGRect(x: x, y: 0, width: width, height: height)
            weatherBgImage.frame = frame
        }
        weatherLabel.frame = CGRect.init(x: 0, y: 0, width: weatherBgImage.width, height: weatherBgImage.height)
    }
}

